package com.justalk.testapplication

import android.annotation.SuppressLint
import android.content.Context
import android.view.MotionEvent
import android.widget.TextView
import java.lang.reflect.Field
import java.lang.reflect.Method

class MyTextView(context: Context?) : androidx.appcompat.widget.AppCompatTextView(context) {




    override fun onTouchEvent(event: MotionEvent): Boolean {
        when (event.action) {
            MotionEvent.ACTION_CANCEL, MotionEvent.ACTION_UP -> postDelayed(Runnable { setSelectHandleDisabled() }, 50) // 延迟50ms，等room显示handle完后，再隐藏
            else -> {
            }
        }
        return super.onTouchEvent(event)
    }

    @SuppressLint("SoonBlockedPrivateApi")
    private fun setSelectHandleDisabled() {
        try {
            val mEditor: Field = TextView::class.java.getDeclaredField("mEditor")
            mEditor.setAccessible(true)
            val `object`: Any = mEditor.get(this)
            val mClass = Class.forName("android.widget.Editor")
            // 选中时handle
            val selectionController: Method = mClass.getDeclaredMethod("getSelectionController")
            selectionController.setAccessible(true)
            val invokeSelect: Any = selectionController.invoke(`object`)
            val hideSelect: Method = invokeSelect.javaClass.getDeclaredMethod("hide")
            hideSelect.invoke(invokeSelect)
            // 插入时handle
            val insertionController: Method = mClass.getDeclaredMethod("getInsertionController")
            insertionController.setAccessible(true)
            val invokeInsert: Any = insertionController.invoke(`object`)
            val hideInsert: Method = invokeInsert.javaClass.getDeclaredMethod("hide")
            hideInsert.invoke(invokeInsert)
        } catch (e: Exception) {
        }
    }
}